const app = require("express")()
const server = require("http").createServer(app)
const io = require("socket.io")(server)
const dayjs = require("dayjs")
const router = require("./router")
const fs = require("fs")
const path = require("path")

// app.use('/', express.static(__dirname + '../'))
app.use("/", router)
app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*")
  res.header("Access-Control-Allow-Headers", "Content-Type")
  next()
})

server.listen(9000, () => {
  console.log("http://localhost:9000")
})

let currentUserList = []

// 连接
io.on("connection", socket => {
  // 获取当前用户IP
  let ip = socket.handshake.address.match(/(?<=ff:).*/)[0]
  // 发送消息，返回当前用户IP
  socket.emit("address", ip)
  currentUserList.push(ip)

  // 向其他人通知该用户加入
  socket.broadcast.emit("system:notice", `${ip} 加入聊天`)
  // 更新当前在线人数
  io.sockets.emit("system:users", currentUserList.length)

  // 监听客户端聊天信息
  socket.on("chat", data => {
    // 只向自己发送消息
    // socket.emit()

    // 向除了自己的所有人发送消息
    // socket.broadcast.emit()

    // 向所有人发送更新消息列表
    io.sockets.emit("add:message", data)
    updateMsgList(data)
  })

  // 监听离线
  socket.on("disconnect", () => {
    let target = currentUserList.findIndex(t => t === ip)
    currentUserList.splice(target, 1)
    socket.broadcast.emit("system:notice", `${ip} 已下线`)
    socket.broadcast.emit("system:users", currentUserList.length)
  })
})

// updateMsgList({ data: "1212", ip: "192.168.44.201", time: "2022-01-12 18:29:44" })

/* 更新数据库消息列表 */
function updateMsgList(msg) {
  let filePath = path.join(__dirname, "../data/demo.json")
  fs.readFile(
    filePath,
    {
      encoding: "utf-8",
    },
    (err, data) => {
      if (err) throw new Error("读取聊天记录失败")
      let currentList = JSON.parse(data)
      currentList.push(msg)
      fs.writeFile(
        filePath,
        JSON.stringify(currentList),
        {
          encoding: "utf-8",
        },
        err => {
          if (err) throw new Error("存储聊天记录失败")
        }
      )
    }
  )
}
